package com.zn.service.impl;

import com.netflix.discovery.converters.Auto;
import com.zn.entity.AgencyBusiness;
import com.zn.entity.OptionAccount;
import com.zn.mapper.AgencyBusinessMapper;
import com.zn.mapper.OptionAccountMapper;
import com.zn.util.Constant;
import com.zn.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author YinJiaWei
 * @version 2019/2/26 18:41
 */
@Component
public class BaseServiceImpl {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseServiceImpl.class);
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private AgencyBusinessMapper agencyBusinessMapper;
    @Autowired
    private OptionAccountMapper optionAccountMapper;

    public String getOrderRefStr(){
        String uniqueIdentification=redisTemplate.opsForValue().get(Constant.BUSINESSUNIQUE);
        if(StringUtils.isBlank(uniqueIdentification)){
            //查询一级平台的唯一识别号
            AgencyBusiness agencyBusiness=agencyBusinessMapper.selectByBusinessLevel();
            uniqueIdentification=agencyBusiness.getUniqueIdentification();
            redisTemplate.opsForValue().set(Constant.BUSINESSUNIQUE,uniqueIdentification);
        }
        Long orderNoInt;
        String orderNoStr = DateUtils.formatDate("yyyyMMdd", new Date());
        String nowDateStr=DateUtils.convertDateToString(new Date());
        String key=Constant.ORDER_NO_LOCA+nowDateStr;
        Object keyFalg=redisTemplate.opsForValue().get(key);
        //如果是新的一天 则从新的100000开始
        if(keyFalg==null){
            redisTemplate.opsForValue().set(key,"100000",24, TimeUnit.HOURS);
            orderNoInt=redisTemplate.opsForValue().increment(key,1);
        }else{
            orderNoInt=redisTemplate.opsForValue().increment(key,1);
        }
        orderNoStr=uniqueIdentification+orderNoStr.substring(2)+orderNoInt;
        return orderNoStr;
    }

    /**
     * 切换当前交易的母账户
     * @param errorCode 9999-开仓已满 8888-持仓已满 31-资金不足
     * @param optionAccountType 母账户类型 1-用户报单 2-跟单报单
     */
    public void switchOptionAccount(String errorCode,Integer optionAccountType){
        try{
            OptionAccount optionAccountStartWhere=new OptionAccount();
            //查询当前开启的母账户信息
            OptionAccount startOptionAccount=optionAccountMapper.selectAccountByStatus(0,optionAccountType);
            //查询备用的母账户信息
            OptionAccount closeOptionAccount=optionAccountMapper.selectAccountByStatus(1,optionAccountType);
            if(startOptionAccount==null || closeOptionAccount==null){
                LOGGER.info("当日交易母账户已全部切换，无账户可切换..............");
            }else {
                /**将开始使用的账户关闭**/
                optionAccountStartWhere.setOptionAccountId(startOptionAccount.getOptionAccountId());
                optionAccountStartWhere.setAccountStatus(1);
                if("31".equals(errorCode)){
                    /**如果时 资金不足的状态码进行账户切换**/
                    optionAccountStartWhere.setCapitalIsFull(1);
                }else{
                    optionAccountStartWhere.setAccountIsFull("9999".equals(errorCode) == true ? 2 : 1);
                }
                //将开启的置为停用
                int flag=optionAccountMapper.updateByPrimaryKeySelective(optionAccountStartWhere);
                if(flag>0){
                    //将停用的 置为开启
                    OptionAccount optionAccountCloseWhere=new OptionAccount();
                    optionAccountCloseWhere.setOptionAccountId(closeOptionAccount.getOptionAccountId());
                    optionAccountCloseWhere.setAccountStatus(0);
                    optionAccountMapper.updateByPrimaryKeySelective(optionAccountCloseWhere);
                } else {
                    LOGGER.info(startOptionAccount.getOptionTradeAccount()+"置为失效失败"+DateUtils.formatDate("yyyy-MM-dd HH:mm:ss",new Date()));
                }
            }
        }catch (Exception e){
            LOGGER.error("switchOptionAccount.....ERROR"+e);
        }
    }

    public Object getRedisSymbol(String today,String contraceCode,int version){
        try{
            Object symbolObj=redisTemplate.opsForHash().get(Constant.OPTION_SYMBOL_INFO + today, contraceCode);
            if(symbolObj==null && version>0){
                Date todayDate=DateUtils.minusDay(DateUtils.convertStringToDate(today), 1);
                version--;
                symbolObj=this.getRedisSymbol(DateUtils.convertDateToString(todayDate), contraceCode,version);
            }
            return symbolObj;
        }catch (Exception e){
            LOGGER.error("getRedisSymbolError........"+e);
            return null;
        }
    }
}
